/**
 * Created by lihongbo on 2017/10/19.
 * http请求配置 使用axios
 */

import axios from 'axios'
import router from '../router'

export const publicUrl = "http://10.0.3.172:18888/";
//axios 配置
//axios.defaults.timeout = 10000;
 axios.defaults.baseURL = publicUrl;


//http request 拦截器
axios.interceptors.request.use(
  config => {
    //const token = getCookie('session');
    //config.data = JSON.stringify(config.data);
    config.headers = {
      // 'Content-Type': 'application/json; charset=UTF-8',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }
    /*if (token) {
      config.params = {'token': token};
    }*/

    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

//http response 拦截器
axios.interceptors.response.use(
  response => {
    //测试http拦截器
    /*if(response.data.success === true) {
      router.push({
        path: '/home/login',
        //参数
        //query: {redirect: 'abc'}
      })
    }*/

    if (response.data.errCode === 2) {
      router.push({
        path: '/',
        //query: {redirect: '/'}
      })
    }
    return response;
  },
  err => {
    return Promise.reject(err.response.data);
  }
);

//axios 请求方法封装
/**
 * get 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function fetch(url, params = {}) {

  return new Promise((resolve, reject) => {
    axios.get(url, {params: params})
      .then(response => {
        //console.log('get success', response.data)
        //if (response.data.retCode === '000000') {
        resolve(response.data);
        //} else {
          //console.log('请求成功，但是数据异常', response.data)
          //reject(response.data)
        //}
      })
      .catch(err => {
        reject(err);
      })

  })

}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
import qs from 'qs'
export function post(url, data = {}) {

  return new Promise((resolve, reject) => {

    axios.post(url, data)
      .then(response => {
          resolve(response.data);
        },
        err => {
          reject(err);
        })

  })

}

/**
 *
 * @param json
 * @returns {string}
 */
export function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&")
}

